package cn.demomaster.quickpicturer.model;
import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * 图片实体类
 */
public class ImageInfo implements Parcelable {

    private String url;
    private Uri uri;
    private boolean isLocalFile;

    public ImageInfo(String url) {
        this.url = url;
        this.isLocalFile = false;
    }

    public ImageInfo(Uri uri) {
        this.uri = uri;
        this.isLocalFile = true;
    }

    protected ImageInfo(Parcel in) {
        url = in.readString();
        uri = in.readParcelable(Uri.class.getClassLoader());
        isLocalFile = in.readByte() != 0;
    }

    public static final Creator<ImageInfo> CREATOR = new Creator<ImageInfo>() {
        @Override
        public ImageInfo createFromParcel(Parcel in) {
            return new ImageInfo(in);
        }

        @Override
        public ImageInfo[] newArray(int size) {
            return new ImageInfo[size];
        }
    };

    public Uri getUri() {
        return uri;
    }

    public void setUri(Uri uri) {
        this.uri = uri;
        this.isLocalFile = true;
    }

    public boolean isLocalFile() {
        return isLocalFile;
    }

    public void setLocalFile(boolean localFile) {
        isLocalFile = localFile;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
        this.isLocalFile = false;
    }

    @Override
    public boolean equals(@Nullable Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        ImageInfo other = (ImageInfo) obj;
        if (isLocalFile) {
            return uri != null && uri.equals(other.uri);
        } else {
            return TextUtils.equals(url, other.url);
        }
    }

    public Object getImageObj(){
        if(uri!=null){
            return uri;
        }
        return url;
    }

    @Override
    public int hashCode() {
        if (isLocalFile) {
            return uri != null ? uri.hashCode() : 0;
        } else {
            return url != null ? url.hashCode() : 0;
        }
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(@NonNull Parcel dest, int flags) {
        dest.writeString(url);
        dest.writeParcelable(uri, flags);
        dest.writeByte((byte) (isLocalFile ? 1 : 0));
    }
}